<?php

namespace App\Middleware;

use App\Constants\ErrorCode;
use App\Model\Admin\Admin;
use App\Service\Users\UsersService;
use Firebase\JWT\JWT;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Redis\RedisFactory;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use App\Model\User;
use Hyperf\Utils\Context;
use Hyperf\HttpServer\Contract\ResponseInterface as Response;
use Hyperf\Di\Annotation\Inject;


class AuthTokenMiddleware implements MiddlewareInterface
{
    /**
     * @Inject
     * @var Response
     */
    protected $response;

    /**
     * @Inject()
     * @var Admin
     */
    protected $adminModel;

    /**
     * @Inject()
     * @var UsersService
     */
    protected $usersService;


    /**
     * @Inject()
     * @var RedisFactory
     */
    protected $redis;


    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $authInfo = null;
        if ($uid = $request->getHeaderLine('autouid')) {
            if($uid == 'admin'){
                $uid = 10005;
            }
            dump($uid);
            Context::set('uid', $uid);
            return $handler->handle($request);
        }
        $token = trim(ltrim($request->getHeaderLine('Authori-zation'), 'Bearer'));
        dump($token);
        if (!$token) {
            //用户未登录
            return $this->response->json(err('用户未登录', ErrorCode::TOEKN_NOT_EXISTS));
        }

        list($headb64, $bodyb64, $cryptob64) = explode('.', $token);

        $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64));
        $uid = $payload->jti->id;
        //取出用户id
        Context::set('uid', $uid);
        return $handler->handle($request);
    }

}